package dryven.request.routing;

import dryven.annotations.DII;
import dryven.config.ApplicationConfiguration;
import dryven.request.controller.ControllerDescription;
import dryven.request.controller.RedirectException;
import dryven.request.controller.paramtransform.ActionParameterTransformer;
import dryven.request.http.Request;
import dryven.request.http.Response;

public class DefaultRoutingService implements RoutingService {
	private Iterable<Router> routers;	//routers that will be searched until a route is found
	private ActionParameterTransformer _parameterTransformer;
	private String _appRootURLPath;
	public DefaultRoutingService(Iterable<Router> routers, ActionParameterTransformer parameterTransformer, 
			@DII(type=ApplicationConfiguration.class,method="getApplicationRootURLPath") String appRootURLPath) {
		super();
		this.routers = routers;
		_parameterTransformer = parameterTransformer;
		_appRootURLPath = appRootURLPath==null?"":appRootURLPath;
	}

	public String controllerToRoute(ControllerDescription cd) {
		for(Router router:routers) {
			String url = router.controllerToRoute(cd, _parameterTransformer);
			if(url!=null) {
				return _appRootURLPath+url;
			}
		}
		throw new RuntimeException(String.format("No router could generate an url for %s.%s", cd.getControllerClass().getName(),cd.getAction().getName()));
	}

	public ControllerDescription routeToController(Request req, Response response) {
		ControllerDescription cd = null;
		try {
			for(Router router:routers) {
				cd = router.routeToController(req, response,_parameterTransformer);
				if(cd!=null) {
					return cd;
				}
			}
		} catch(RedirectException e) {
			return e.getForward();
		}
		return null;
	}
	
	
}
